package com.boarsoft.boar.code.mac.flow.biz.impl;

import java.util.List;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.code.entity.WrapHandlerInfo;
import com.boarsoft.boar.code.mac.flow.biz.WrapHandlerInfoBiz;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("wrapHandlerInfo")
public class WrapHandlerInfoBizImpl extends SimpleBizImpl implements WrapHandlerInfoBiz {

	@Override
	@Transactional
	public String save(WrapHandlerInfo wrapHandlerInfo) {
		try {
			int count = findByCodeAndKey(wrapHandlerInfo.getCode(), wrapHandlerInfo.getKey());
			if (Util.strIsEmpty(wrapHandlerInfo.getId()) || //
					(wrapHandlerInfo.getType() == 1 && count == 0)) {
				wrapHandlerInfo.setId(null);
				dao.save(wrapHandlerInfo);
			} else {
				dao.update(wrapHandlerInfo);
			}
			return wrapHandlerInfo.getId();
		} catch (DataIntegrityViolationException e) {
			log.error("保存失败", e);
			return null;
		}
	}

	@Transactional(readOnly = true)
	public int findByCodeAndKey(String code, String key) {
		return dao.getTotal(WrapHandlerInfo.class, "and code= '" + code + "'" + " and key = '" + key + "'");
	}

	@Transactional(readOnly = true)
	@Override
	public List<WrapHandlerInfo> find(String code, String key, int type, String appId) {
		return dao.list(WrapHandlerInfo.class, "and code='" + code + "'" + " and key = '" + key + "'" + " and type = " + type
				+ " and appId = '" + appId + "'");
	}

	@Transactional(readOnly = true)
	@Override
	public PagedResult<WrapHandlerInfo> list(String key, String orderBy, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from ").append(WrapHandlerInfo.class.getName());
		sb.append(" s where 1=1");
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and (s.key like '%").append(key);
			sb.append("%' or s.code like '%").append(key);
			sb.append("%')");
		}
		int total = dao.getTotal("select count(s.id)".concat(sb.toString()));
		// if (Util.strIsNotEmpty(orderBy)) {
		// sb.append(" order by ").append(orderBy);
		// } else {
		// sb.append(" order by name");
		// }
		List<WrapHandlerInfo> lt = dao.list("select s".concat(sb.toString()), pageNo, pageSize);
		return new PagedResult<>(total, lt, pageNo, pageSize);
	}
}
